var express = require('express');
var router = express.Router();
var multer  = require('multer');
var config = require('../config');
var fileName;
var storage = multer.diskStorage({
  //设置上传后文件路径，uploads文件夹会自动创建。
  destination: 'public/upload',
  //给上传文件重命名，获取添加后缀名
  filename: function (req, file, cb) {
      var fileFormat = (file.originalname).split(".");
      fileName = new Date().getTime() + "." + fileFormat[fileFormat.length - 1];
      cb(null, fileName);
  }
}); 
//添加配置文件到muler对象。
var upload = multer({
  storage,
  limits:{}
});

router.post('/upload', upload.single('file'), function (req, res) {
  if (!req.file) {
      return res.send({
        code: 1,
        message: 'No file received'
      });
  } else {
      return res.send({
          code: 0,
          message: '上传成功',
          url: `http://${config.HOST}:3000/upload/${fileName}`
      })
  }
})

/* GET users listing. */

router.get('/text', function(req, res, next) {
  res.json({
    message: 'Hello 小雄子'
  })
});
module.exports = router;